package edu.thu.thss.rsa.yxy;

import java.math.BigInteger;

public class PrivateKey extends PublicKey{
	private BigInteger d; // decryption exponent
	
	public PrivateKey(BigInteger d, BigInteger n) {
		super(n);
		this.d = d;
	}
	
	public BigInteger getN() {
		return n;
	}
	
	public BigInteger getD() {
		return d;
	}

	// RSADecrypt: decryption function, fast CRT version
	public BigInteger RSADecrypt(BigInteger c) {
		return c.modPow(d, n);
	}

	// RSASign: same as decryption for RSA (since it is a symmetric PKC)
	public BigInteger RSASign(BigInteger m) {
		// return m.modPow(d, n);
		return RSADecrypt(m); // use fast CRT version
	}

	public BigInteger RSASignAndEncrypt(BigInteger m, PublicKey other) {
		// two ways to go, depending on sizes of n and other.getN()
		if (n.compareTo(other.getN()) > 0)
			return RSASign(other.RSAEncrypt(m));
		else
			return other.RSAEncrypt(RSASign(m));
	}

	public BigInteger RSADecryptAndVerify(BigInteger c, PrivateKey other) {
		// two ways to go, depending on sizes of n and other.getN()
		if (n.compareTo(other.getN()) > 0)
			return other.RSAVerify(RSADecrypt(c));
		else
			return RSADecrypt(other.RSAVerify(c));
	}
}
